﻿#include "QlyVideoReader.h"

QlyVideoReader::QlyVideoReader(QString fileName)
{
    m_fileName = fileName;
    m_type << AVMEDIA_TYPE_VIDEO;
}

QlyVideoReader::QlyVideoReader()
{
    m_type << AVMEDIA_TYPE_VIDEO;
}

double QlyVideoReader::frameRate()
{
    return m_videoContext.stream(0).frameRate();
}

bool QlyVideoReader::openFile(QString url)
{
    errorcode = m_videoContext.openFile(url);
    if(errorcode < 0)
    {
        qWarning() << "m_videoContext.openFile(url) failed, errorcode = " << m_videoContext.errorString();
        return false;
    }
    QVector<QlyAVStream> inStreams = m_videoContext.findStreams(m_type);
    if(inStreams.isEmpty())
    {
        return false;
    }
    errorcode = m_codec.findDecoder(inStreams[0].codecpar()->codec_id);
    if(errorcode < 0)
    {
        qWarning() << "m_codec.findDecoder failed, errorcode = " << errorcode;
        return false;
    }
    errorcode = m_codecContext.openCodec(&m_codec, inStreams[0].codecpar());
    if(errorcode < 0)
    {
        qWarning() << "m_codecContext.openCodec failed, errorcode = " << errorcode;
        return false;
    }

    return true;
}

bool QlyVideoReader::readFrame(QlyAVFrame &frame)
{
    bool ret = false;
    if(!m_FrameQueue.isEmpty())
    {
        frame = m_FrameQueue.dequeue();
        return true;
    }
    QlyAVPacket pkt;
    while(m_FrameQueue.isEmpty())
    {
        ret = m_videoContext.readPacket(pkt, m_type);
        if(!ret) return false;
        ret = m_codecContext.decodePacket(pkt.ptr(), m_FrameQueue);
        if(!ret) return false;
    }
    if(!m_FrameQueue.isEmpty())
    {
        frame = m_FrameQueue.dequeue();
        return true;
    }
    return false;
}
